<template>
  <div class="home">
    <!--------------------------- 根据用户名搜索 -------------------------------->
    <el-card style="margin-bottom: 40px" class="box-card" shadow="hover">
      <div style="display: flex">
        <div style="margin-right: 30px">
          <label class="el-form-item__label"></label>
          <el-input
            style="width: 270px"
            placeholder="请输入用户名"
            v-model="params.username"
            clearable
          ></el-input>
        </div>
        <el-button style="margin-left: 5px" type="primary" @click="showByName" >
          <i class="el-icon-search"></i>搜索
        </el-button>
        <el-button style="margin-left: 8px" @click="reset">
          <i class="el-icon-refresh-right"></i>重置
        </el-button>

      </div>
    </el-card>

    <!--------------------------- 用户详情 添加用户按钮-------------------------------->
    <el-card class="box-card" shadow="hover" >
      <div style="display: flex; margin-bottom: 10px">
        <span style="font-weight: bold">用户详情</span>
        <el-button
          style="margin-left: auto; margin-right: 40px"
          type="primary"
          @click="addDialogVisible = true"
        >
          <i class="el-icon-circle-plus-outline"></i>
          添加用户</el-button
        >
      </div>

      <!--------------------------- 显示用户信息-------------------------------->
      <el-table :data="userList" stripe border height="350">
        <el-table-column prop="id" label="用户编号"></el-table-column>
        <el-table-column prop="username" label="用户名称"></el-table-column>
        <el-table-column
          prop="createdTime"
          label="注册时间"
        ></el-table-column>
        <el-table-column
          prop="isDelete"
          label="账号状态"
        >
          <template slot-scope="scope">
            <el-switch v-model="scope.row.switchValue"
                       @change="userStateChange(scope.row.id ,scope.row.switchValue)">
            </el-switch>
          </template>
        </el-table-column>

        <!--------------------------- 重置密码按钮-------------------------------->
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="getResetId(scope.row.id)">
            <i class="el-icon-refresh-right"></i>重置密码
          </el-button>
          <el-dialog
              title=""
              :visible.sync="resetDialogVisible"
              width="30%"
              center
          >
            <p class="confirm-text">确定要重置密码吗？</p>
            <span slot="footer" class="dialog-footer">
        <el-button @click="resetPassword" type="primary">确定</el-button>
        <el-button @click="resetDialogVisible = false">取消</el-button>
      </span>
          </el-dialog>
          </template>
        </el-table-column>
      </el-table>

      <!---------------------------  分页  -------------------------------->
      <div style="margin-top: 20px; display: flex">
        <!--分页区域-->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="params.pageIndex"
            :page-sizes="[1, 5, 10, 20]"
            :page-size="params.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        >
        </el-pagination>
      </div>


      <!--------------------------- 添加用户 -------------------------------->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed" width="30%">
        <el-form
          :model="addUserForm"
          label-width="100px"
          ref="addUserFormRef"
          :rules="addUserFormRules"
        >
          <el-form-item label="用户名" prop="username" >
            <el-input
              v-model="addUserForm.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="addUserForm.phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮件地址" prop="email">
            <el-input
              v-model="addUserForm.email"
              placeholder="请输入邮件地址"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
      
      <script>
import request from "@/api/request";

export default {
  name: "userShow",
  data() {
    // 验证添加用户邮箱的规则
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (!value) {
        return cb(); // 输入为空，通过验证
      }
      if (regEmail.test(value)) {
        return cb(); // 符合邮箱格式，通过验证
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证添加用户手机的规则
    const checkPhone = (rule, value, cb) => {
      // 验证手机的正则表达式
      const regPhone =
          /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
      if (!value) {
        return cb(); // 输入为空，通过验证
      }
      if (regPhone.test(value)) {
        return cb()// 符合手机号格式，通过验证
      }
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      //定义获取用户列表参数(params) query:查询 pageIndex:当前页数 pageSize:每页显示数据数
      params: {
        pageIndex: 1,
        pageSize: 5,
        query:'',
        username:''
      },
      //获取用户列表数据,存放到userList中,查询条数放到total中
      userList: [],
      total: 0,
      //控制添加用户对话框的显示与隐藏 默认关闭
      addDialogVisible:false,
      //重置密码
      resetDialogVisible:false,
      //重置密码得到当前行id
      ID:'',
      //判断是查询所有用户还是用户名模糊搜索查询
      isChange:true,
      // 添加用户的表单数据
      addUserForm: {
        username: '',
        email: '',
        phone: '',
      },
      // 添加用户的表单规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '用户名的长度不超过10个字符',
            trigger: 'blur',
          },
        ],
        email: [
          // { required: false, trigger: 'blur' },
          { required: false,validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          // { required: true, message: '请输入合法的手机号码11', trigger: 'blur' },
          { required: false, validator: checkPhone , trigger: 'blur'},
        ],
      },
    };
  },
  created() {
    this.load();
  },
  methods: {
    // 添加用户，点击添加按钮，,validate(预校验)
    addUser() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return
        // 成功后向api发出添加用户的网络请求
        const jsonData = JSON.stringify(this.addUserForm);
        request
            .post("user/add", jsonData, {})
            .then((res) => {
              console.log(res);
              if (res.code === 20000) {
                this.$message.success('添加用户成功!')
                console.log("添加成功");
                // 隐藏添加用户的对话框
                this.addDialogVisible = false;
                // 重新获取用户列表
                this.load();
              } else if (res.code === 40901) {
                this.$message.error('该用户名已存在，添加用户失败!')
              }
            })
            .catch((error) => {
              console.error("未知错误", error);
              // 可以在这里处理请求失败的情况，例如提示用户请求失败或进行其他逻辑处理
            });
      })
    },
    //重置密码得到当前行id保存下来
    getResetId(id){
      this.ID = id;
      this.resetDialogVisible = true;
    },
    //重置密码
    resetPassword() {
      const id= this.ID;
      if (id !== null) {
        request
            .put("user/reset/" + id, {})
            .then((res) => {
              console.log(res);
              if (res.code === 20000) {
                this.$message.success('重置用户密码成功!');
              } else {
                this.$message.error('重置用户密码失败!');
              }
              // 在请求成功或失败后关闭对话框
              this.resetDialogVisible = false;
            })
            .catch((error) => {
              // 处理请求错误
              console.error("请求出错:", error);
              this.$message.error('重置用户密码时发生错误!');
              this.resetDialogVisible = false;
            });
      } else {
        // 如果id为null，则不发送请求，直接关闭对话框并给出提示
        this.$message.warning('用户ID为空，无法重置密码!');
        this.resetDialogVisible = false;
      }
    },
    //改变用户账号状态
    userStateChange(id, switchValue){
      console.log("修改状态id:" + id);
      //启用
      if (switchValue) {
        request
            .put("user/start/" + id, {})
            .then((res) => {
              console.log(res);
              if (res.code === 20000) {
                this.load();
                this.$message.success('启用用户成功!');
              } else {
                this.$message.error('启用用户失败!');
              }
            })
            .catch((error) => {
              // 处理请求错误
              console.error("请求出错:", error);
              this.$message.error('启用用户时发生错误!');
            });
      } else {//按钮为关闭状态
        // 禁用
        request
            .put("user/stop/" + id, {})
            .then((res) => {
              console.log(res);
              if (res.code === 20000) {
                this.load();
                this.$message.success('禁用用户成功!');
              } else {
                this.$message.error('禁用用户失败!');
              }
            })
            .catch((error) => {
              // 处理请求错误
              console.error("请求出错:", error);
              this.$message.error('禁用用户时发生错误!');
            });
      }
    },
    //查询显示所有用户
    load() {
      const params = {
        query: this.params.query.toString() // 如果query不是字符串，则转换为字符串
      };
      const requestBody = {
        pageIndex: this.params.pageIndex,
        pageSize: this.params.pageSize,
      };
      request
          .post("user/show", requestBody, {params})
          .then((res) => {
            console.log(res);
            if (res.code === 20000) {
              // 设置 userList 和 total
              this.userList = res.data.data;
              this.total = res.data.count;
              //改变值用于判断页码
              this.isChange = true;
              // 遍历 userList，为每个用户对象设置 switchValue
              this.userList.forEach(user => {
                //启用
                if(user.isDelete === 0){
                  user.switchValue = true;
                }else{
                  //禁用
                  user.switchValue = false;
                }
              });
            }
          })
          .catch((error) => {
            console.error("请求出错:", error);
          });
    },
    //根据用户名查询
    showByName(){
      const params = {
        username: this.params.username, // 作为查询参数发送
      };
      const requestBody = {
        pageIndex: this.params.pageIndex,
        pageSize: this.params.pageSize,
      };
      request
          .post("user/showByName",requestBody, {params})
          .then((res) => {
            console.log(res);
            if (res.code === 20000) {
              // 设置 userList 和 total
              this.userList = res.data.data;
              this.total = res.data.count;
              //便于分页查询
              this.isChange = false;
              // 遍历 userList，为每个用户对象设置 switchValue
              this.userList.forEach(user => {
                //启用
                if(user.isDelete === 0){
                  user.switchValue = true;
                }else{
                  //禁用
                  user.switchValue = false;
                }
              });
            }
          })
          .catch((error) => {
            console.error("请求出错:", error);
          });
    },
    // 监听添加用户对话框的:close关闭事件,清除数据(resetFields)
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields()
    },
    //重置搜索
    reset() {
      //回到第一页
      this.params.pageIndex = 1;
      //重新加载
      this.load();
      //清空搜索框
      this.params.username = '';
    },
    // 换页功能
    // 监听page页码值改变的事件
    handleCurrentChange(newPage) {
      console.log("newPage:"+newPage)
      this.params.pageIndex = newPage
      if(this.isChange){
        this.load()
      }else{
        this.showByName()
      }
    },
    // 监听pageSize改变的事件
    handleSizeChange(newSize) {
      console.log("newSize:"+newSize)
      this.params.pageSize = newSize
      if(this.isChange){
        this.load()
      }else{
        this.showByName()
      }
    },
  },
};
</script>
      
      <style scoped>
.el-form-item__label {
  align-items: flex-start;
  box-sizing: border-box;
  color: var(--el-text-color-regular);
  display: inline-flex;
  flex: 0 0 auto;
  font-size: var(--el-form-label-font-size);
  height: 32px;
  justify-content: flex-end;
  line-height: 32px;
  padding: 0 12px 0 0;
  font-weight: bold;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.confirm-text {
  font-size: 18px; /* 调整为适合您需求的字体大小 */
  text-align: center; /* 文本居中 */
  margin: 0; /* 移除默认的边距，如果有的话 */
}
      </style>